package com.example.administrator.activity.parcitise.Storage;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.activity.R;

public class SPActivity extends AppCompatActivity {

        Button btn_read,btn_write;
        TextView textView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_sp);
            btn_read=findViewById(R.id.ch3_file_sp_btn_read);
            btn_write=findViewById(R.id.ch3_file_sp_btn_write);
            textView=findViewById(R.id.ch3_file_sp_tv);

            View.OnClickListener clickListener=new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (v.getId()){
                        case R.id.ch3_file_sp_btn_write:
                            write();
                            break;
                        case R.id.ch3_file_sp_btn_read:
                            read();
                            break;
                    }
                }
            };
            btn_read.setOnClickListener(clickListener);
            btn_write.setOnClickListener(clickListener);
        }

        /**
         * 从SharePreferrce读取内容展示在TextView
         */
        private void read() {
            SharedPreferences sp=getSharedPreferences("slsher",MODE_PRIVATE);
            String name=sp.getString("name",null);
            int age=sp.getInt("age",0);
            textView.setText(name+""+age);
        }

        /**
         * 把内容写入到SharPrefercences
         */
        private void write() {
            SharedPreferences sp=this.getSharedPreferences("slsher",MODE_PRIVATE);
            SharedPreferences.Editor editor=sp.edit();
            editor.putString("name","zhangsan");
            editor.putString("pwd","123");
            editor.commit();
            Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
        }

    }
